import React, { Component } from 'react';
import GoBack from '@/components/TheGoBack'
import { Button, Checkbox, Form, Input, DatePicker, Select, Switch, Modal, Radio, Tag, Space, InputNumber, message } from 'antd';
import { apiGetGoodsList, apiAdd, apiEdit, apiGetGoodsDetail, apiView } from '@/request/marketingTool'
import moment from 'moment'
import '../style.scss'
const { Option, OptGroup } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker
export default class BargainAdd extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.state = {
            goodsList: [],
            productSku: {},
            currentSku: {},
            loading: false
        }
    }
    componentDidMount() {
        this.getData()
        this.setState({
            id: this.props.match.params.id
        }, () => {
            if (this.state.id !== 'null') {
                this.apiView(this.state.id)

            }
        })


    }
    async apiView(id) {
        let res = await apiView({ id })
        if (res.code === 0) {

            let { goodsId,type,cutMode, cutPriceLow, dataId, startTime, endTime, expire, originStock, cutPriceType, userNum, userBuyLimit, newCutCount } = res.data

            this.apiGetGoodsDetail(goodsId, dataId)
            this.formRef.current.setFieldsValue({
                goodsId,
                type,
                cutMode,
                cutPriceLow: cutPriceLow / 100,
                activityTime: [moment(startTime), moment(endTime)],
                expire,
                originStock: originStock === -1 ? undefined : originStock,
                cutPriceType,
                userNum,
                userBuyLimit: userBuyLimit === -1 ? undefined : userBuyLimit,
                newCutCount

            })
        }
    }
    async apiGetGoodsDetail(goodsId, skuId) {
        
        let res = await apiGetGoodsDetail({ goodsId })
        if (res.code === 0 ) {
            if(res.data.skuInfo === null) {
                let that = this
                Modal.error({
                    title: '管理员无商品sku,禁止添加砍价活动!',
                    okText: '确定',
                    onOk() {
                        that.props.history.goBack()
                    }
                  });
                return
            }
            if (skuId) {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo.filter(item => item.SKUId === skuId)[0]
                })
            } else {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo[0]
                })
            }

        }
        // if (res.code === 0) {
        //     if (skuId) {
        //         this.setState({
        //             productSku: res.data,
        //             currentSku: res.data.skuInfo.filter(item => item.SKUId === skuId)[0]
        //         })
        //     } else {
        //         this.setState({
        //             productSku: res.data,
        //             currentSku: res.data.skuInfo[0]
        //         })
        //     }

        // }
    }
    async getData() {
        let res = await apiGetGoodsList()
        if (res.code === 0) {
            this.setState({
                goodsList: res.data
            })
        }
    }
    selectFilter(input, option) {
        return option.children.toLowerCase().includes(input.toLowerCase())
    }
    goodsChange(e, row) {
        this.apiGetGoodsDetail(e)
    }
    triggerSkuTag(row) {
        if (this.state.id !== 'null') {
            return
        }
        this.setState({
            currentSku: row
        })
    }
    onFinish(values) {
        let { id, currentSku, productSku } = this.state

        let applyData = {
            title: productSku.goodsInfo.goodsName,
            dataSkuImg: currentSku.imageFile ? currentSku.imageFile.split(',')[0] : '',
            goodsId: values.goodsId,
            dataId: currentSku.SKUId,
            type:values.type,
            cutMode: values.cutMode,
            cutPriceLow: Number(values.cutPriceLow * 100).toFixed(0),
            startTime: moment(values.activityTime[0]).format('yyyy-MM-DD HH:mm:ss'),
            endTime: moment(values.activityTime[1]).format('yyyy-MM-DD HH:mm:ss'),
            expire: values.expire,
            originStock: values.originStock === undefined||values.originStock === null ||values.originStock === '' ? -1 : values.originStock,
            cutPriceType: values.cutPriceType,
            userNum: values.userNum,
            newCutCount: values.newCutCount,
            userBuyLimit: values.userBuyLimit === undefined ||values.userBuyLimit === null ||values.userBuyLimit === ''? -1 : values.userBuyLimit,
            skuJson: JSON.stringify(currentSku),
            cutPrice: Number(currentSku.skuCurrentPrice).toFixed(0),
            price: Number(currentSku.skuOriginalPrice).toFixed(0),
        }
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "是否确认提交？",
            onOk: async () => {
                this.setState({ loading: true })
                let res;
                if (id == 'null') {
                    res = await apiAdd(applyData)
                } else {
                    applyData.id = id
                    res = await apiEdit(applyData)
                }
                if (res.code === 0) {
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                    this.props.history.goBack()
                }
                this.setState({ loading: false })
            }
        });

    }
    check(rules, value, callback) {
        let cutPriceLow = this.formRef.current.getFieldValue('cutPriceLow') * 100
        let userNum = this.formRef.current.getFieldValue('userNum')
        let skuCurrentPrice = this.state.currentSku.skuCurrentPrice
        if (cutPriceLow >= skuCurrentPrice) {
            callback('砍价最低价不可大于等于商品售价！')
        } else if ((skuCurrentPrice - cutPriceLow) < userNum) {
            callback('无法根据[砍价最低价]分配砍价人数！')
        } else {
            return Promise.resolve()
        }
    }
    checkuserNum(rules, value, callback) {
        let cutPriceLow = this.formRef.current.getFieldValue('cutPriceLow') * 100
        let skuCurrentPrice = this.state.currentSku.skuCurrentPrice
        let userNum = this.formRef.current.getFieldValue('userNum')
        if ((skuCurrentPrice - cutPriceLow) < userNum) {
            callback('无法根据[砍价最低价]分配砍价人数！')
        } else {
            return Promise.resolve()
        }
    }
    render() {
        const { id, goodsList, productSku, currentSku, loading } = this.state
        return (
            <div className="p-layout-box">
                <GoBack history={this.props.history} title="新增砍价商品" />
                <Form
                    style={{ marginTop: 20 }}
                    ref={this.formRef}
                    initialValues={{
                        type: 0,
                        cutMode: 0,
                        cutPriceType: 0
                    }}
                    labelCol={{
                        span: 4,
                    }}
                    wrapperCol={{
                        span: 12,
                    }}
                    onFinish={(values) => this.onFinish(values)}
                    autoComplete="off"
                >
                    <Form.Item
                        label="选择商品"
                        name="goodsId"
                        rules={[
                            {
                                required: true,
                                message: '请选择商品!',
                            },
                        ]}
                    >
                        <Select
                            disabled={id !== 'null'}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) => this.selectFilter(input, option)}
                            style={{
                                width: 400,
                            }}
                            onChange={(e, obj) => this.goodsChange(e, obj)}
                            placeholder="请选择商品"
                        >
                            {
                                goodsList.map(item => <Option option={item} key={item.goodsId} value={item.goodsId}>{item.goodsName}</Option>)
                            }
                        </Select>

                    </Form.Item >
                    {
                        productSku.hasOwnProperty('goodsInfo') ?
                            <Form.Item
                                wrapperCol={{
                                    offset: 4,
                                    span: 16,
                                }}
                            >
                                <div className='goodsDesc'>
                                    <div className='info'>
                                        <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                                        <div className="goodsInfo">
                                            <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                            <div className='price' >
                                                价格：<React.$Price price={currentSku.skuCurrentPrice} />&nbsp;&nbsp;
                                                <React.$Price price={currentSku.skuOriginalPrice} del={true} />
                                            </div>
                                            <div className='stock' >
                                                库存：{currentSku.stock}
                                            </div>
                                        </div>
                                    </div>
                                    <div className='goodsSku'>
                                        {
                                            productSku.skuInfo.map(item =>
                                                <Tag className='tag' key={item.SKUId} style={{ cursor: id == 'null' ? 'pointer' : 'not-allowed' }} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} onClick={() => this.triggerSkuTag(item)}>
                                                    {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                </Tag>
                                            )
                                        }

                                    </div>
                                </div>
                            </Form.Item> : null
                    }
                    <Form.Item
                        label="砍价类型"
                        name="type"
                    >
                        <Radio.Group >
                            <Space >
                                <Radio value={0}>一元</Radio>
                                <Radio value={1}>底价</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="砍价模式"
                        name="cutMode"
                    >
                        <Radio.Group >
                            <Space >
                                <Radio value={0}>无需砍到底价即可购买</Radio>
                                <Radio value={1}>砍到底价才可购买</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="砍价最低价"
                        name="cutPriceLow"
                        rules={[
                            {
                                required: true,
                                message: '请输入砍价最低价!',
                            },
                            {
                                required: true,
                                validator: this.check.bind(this)
                            }
                        ]}
                    >
                        <InputNumber style={{
                            width: 400,
                        }} placeholder='请输入砍价最低价' min={0.01} precision={2} />
                    </Form.Item>
                    <Form.Item
                        label="活动时间"
                        name="activityTime"
                        rules={[
                            {
                                required: true,
                                message: '请选择活动时间!',
                            },
                        ]}
                    >
                        <RangePicker format="YYYY-MM-DD HH:mm:ss" style={{
                            width: 400,
                        }} showTime />
                    </Form.Item>
                    <Form.Item
                        label="砍价有效期"
                        name="expire"
                        rules={[
                            {
                                required: true,
                                message: '请选择砍价有效期!',
                            },
                        ]}
                    >
                        <InputNumber style={{
                            width: 400,
                        }} addonAfter={'小时'} precision={0} min={0} />
                    </Form.Item>
                    <Form.Item
                        label="砍价库存"
                        name="originStock"

                    >
                        <InputNumber style={{
                            width: 400,
                        }} placeholder='无限制' precision={0} min={1} />
                    </Form.Item>
                    <Form.Item
                        label="帮砍价格"
                        name="cutPriceType"

                    >
                        <Radio.Group >
                            <Space >
                                <Radio value={0}>随机金额</Radio>
                                <Radio value={1}>固定金额</Radio>
                            </Space>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="帮砍人数"
                        name="userNum"
                        rules={[
                            {
                                required: true,
                                message: '请输入帮砍人数!',
                            },
                            {
                                required: true,
                                validator: this.checkuserNum.bind(this)
                            }
                        ]}
                    >
                        <InputNumber style={{
                            width: 400,
                        }} placeholder='请输入帮砍人数' precision={0} min={0} />
                    </Form.Item>
                    <Form.Item
                        label="每人限购"
                        name="userBuyLimit"
                    >
                        <InputNumber style={{
                            width: 400,
                        }} placeholder='无限制' precision={0} min={0} />
                    </Form.Item>
                    <Form.Item
                        label="新人一刀抵多刀"
                        name="newCutCount"
                        rules={[
                            {
                                required: true,
                                message: '请输入',
                            },
                        ]}
                    >
                        <InputNumber style={{
                            width: 400,
                        }} placeholder='' precision={0} step={1} min={1} />
                    </Form.Item>
                    <Form.Item
                        wrapperCol={{
                            offset: 4,
                            span: 16,
                        }}
                    >
                        <Button type="default" onClick={() => this.props.history.go(-1)} style={{ 'marginRight': 20 }}>
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
}
